101 Algorithms Questions You Must Know: Tricky Questions. Fun Solutions. by Arora Amrinder
Author:Arora, Amrinder [Arora, Amrinder]
Language: eng
Format: epub
Published: 2018-08-13T16:00:00+00:00
Question 59. Love (Skip) Thy Neighbor
Given a list of n positive numbers, your objective is to select the set of numbers that maximizes the sum of selected numbers, given the constraint that we cannot select two numbers that are located adjacent to each other. Describe a linear time algorithm for this problem.
Solution
Suppose the given array is a , with values a[1], .., a[n]. Let S(j) denote the maximum sum of numbers that can be achieved using first j numbers, such that no adjacent numbers are selected.
We observe that S(j) can be defined recursively as follows:
S(j) = max {S(j-1), S(j-2) + a[j] }
The two arguments in the max function correspond to the cases where we select (j – 1) -th element and forego j -th element, or we select j -th element and forego (j – 1) -th element.
This recursive relationship can be seeded with the following two base values:
S(1) = a[1]
S(2) = max{a[1], a[2]}
We observe that the principle of optimality clearly holds in this case, as if S(j) is optimal, then the sub-solutions S(j-1) and S(j-2) must be optimal as well.
Therefore, the following dynamic programming algorithm can be used.
S[1] = a[1]
S[2] = max{a[1], a[2]}
for j = 3 to n
S[j] = max {S[j-1], S[j-2]+a[j]
// Our final answer is S[n]
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
The Art of Coaching Workbook by Elena Aguilar(49923)
Trainspotting by Irvine Welsh(20876)
Twilight of the Idols With the Antichrist and Ecce Homo by Friedrich Nietzsche(18234)
Fangirl by Rainbow Rowell(8685)
Periodization Training for Sports by Tudor Bompa(7832)
Change Your Questions, Change Your Life by Marilee Adams(7272)
This Is How You Lose Her by Junot Diaz(6369)
Asking the Right Questions: A Guide to Critical Thinking by M. Neil Browne & Stuart M. Keeley(5273)
Grit by Angela Duckworth(5224)
Red Sparrow by Jason Matthews(5122)
Paper Towns by Green John(4718)
Room 212 by Kate Stewart(4665)
Ken Follett - World without end by Ken Follett(4384)
The Sports Rules Book by Human Kinetics(4015)
Housekeeping by Marilynne Robinson(3987)
Papillon (English) by Henri Charrière(3829)
Double Down (Diary of a Wimpy Kid Book 11) by Jeff Kinney(3815)
The Motorcycle Diaries by Ernesto Che Guevara(3724)
Exercise Technique Manual for Resistance Training by National Strength & Conditioning Association(3715)
